<template>
	<van-cell-group v-show="display">
		<van-field v-model="form.phone" label="手机号码" placeholder="请输入手机号" clearable />
		<van-field v-model="form.captcha" label="验证码" placeholder="请输入图形验证码" clearable>
			<img slot="icon" v-bind:src="captcha" v-on:click="randCaptcha">
		</van-field>
		<div class="van-cell van-field">
			<van-button @click="formValidate" type="primary" :loading="btn.loading" :disabled="btn.disabled" size="large" class="mt-10">下一步</van-button>
		</div>
	</van-cell-group>
</template>
<script>
	import { Field,Button,Cell,CellGroup } from 'vant';

	import Va from 'async-validator';

	const formRule = {
	  	phone: [
	  		{type: "string", required: true,message :'请填写注册手机号码'},
	  		{validator(rule, value, callback, source, options) {
		      	if(!(/^(139|138|137|136|135|134|147|150|151|152|157|158|159|178|182|183|184|187|188|130|131|132|155|156|185|186|145|176|133|153|177|173|180|181|189|170|171)\d{8}$/.test(value))){
	               	callback('手机号码格式错误');
	            }
	            callback();
		    }}
	  	],
	  	captcha : [
	  		{type : "string" , required: true , message : '请填写图片验证码'},
	  		{ length : 4,message : '验证码4位'}
	  	],
	};

	export default {
		props :{
			display :  {
	            type: Boolean,
	            default : false,
	            required : true,
	        },
	        callback:{
	        	type: Function,
	            required : true,
	        }
		},
		components:{
			[Field.name]: Field,
			[Button.name]: Button,
			[CellGroup.name] : CellGroup,
			[Cell.name] : Cell,
        },
        data (){
	        return{
	            form :{
	            	phone : '',
	            	captcha : '',
	            },
	            btn :{
	            	disabled : false,
	            	loading : false,
	            },
	            captcha : '',
	        }
	    },
	    methods: {
			//数据验证
			formValidate(){
				new Va(formRule).validate(this.form, (errors, fields) => {
				  	if(errors) {
				  		this.$toast(errors[0].message);
				  	}else{
				  		this.callback(this.form);
				  	}
				});
			},
			//随机验证码
			randCaptcha(){
	        	this.captcha = '/captcha?'+new Date().getTime();
	        },
	    },
	    created :function(){
	    },
	    watch :{
	    	display :{
	    		immediate:true,
			    handler:function(newVue,oldVue){
			     	if(!newVue){  
		    			this.form.phone = '';
		    			this.form.captcha = '';
		    		}else{
		    			this.randCaptcha();
		    		}
			    }
	    	},
	    }
	}
</script>
<style>
	.checkphone .btn{margin-top: 15px;}
</style>